/*
 * ScriptCompiler.java
 *
 * Created on July 18, 2007, 1:55 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.www.util.script;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.infoset.xml.InfosetFactory;
import org.infoset.xml.ItemDestination;
import org.infoset.xml.sax.SAXEventGenerator;

/**
 *
 * @author alex
 */
public class ScriptCompiler
{
   static Logger LOG = Logger.getLogger(ScriptCompiler.class.getName());
   static String XSLT = "atom-script2xsl.xsl";
   URL compilerXSLT;
   TransformerFactory factory;
   
   /** Creates a new instance of ScriptCompiler */
   public ScriptCompiler()
   {
      factory = TransformerFactory.newInstance();
      compilerXSLT = getClass().getResource(XSLT);
      if (compilerXSLT==null) {
         throw new RuntimeException("Cannot get "+XSLT);
      }
   }
   
   public Transformer compileToTransformer(Source source)
      throws IOException,TransformerConfigurationException,TransformerException
   {
      
      StringWriter sw = new StringWriter();
      compile(source,new StreamResult(sw));
      if (LOG.isLoggable(Level.FINE)) {
         LOG.fine("Result for template:\n"+sw.toString());
      }
      return factory.newTransformer(new StreamSource(new StringReader(sw.toString()),source.getSystemId()));
   }
   
   public void compileToDestination(Source source,ItemDestination sink)
      throws IOException,TransformerConfigurationException,TransformerException
   {
      
      SAXEventGenerator generator = new SAXEventGenerator();
      generator.setItemConstructor(InfosetFactory.getDefaultInfoset().createItemConstructor());
      generator.setItemDestination(sink);
      compile(source,new SAXResult(generator));
   }
   
   public void compile(Source source,Result result)
      throws IOException,TransformerConfigurationException,TransformerException
   {
      InputStream is = compilerXSLT.openStream();  
      Reader r = new InputStreamReader(is,"UTF-8");
      Transformer compileTemplate = factory.newTransformer(new StreamSource(r,compilerXSLT.toString()));  
      r.close();
      compileTemplate.transform(source,result);
   }
   
}
